#define DEBUG
#include <cstdio>

using namespace std;

const int maxn=200000, maxm=100000;

int max(int a, int b) {
  return a>b ? a : b;
}

void sort(int *a, int *b, int l, int r) {
  int i = l, j = r, mid = a[(l+r)/2], temp;
  for (; i<=j; ) {
    for (; a[j]>mid; j--);
    for (; a[i] < mid; i++);
    if (i <= j) {
      temp = a[i], a[i] = a[j], a[j] = temp;
      temp = b[i], b[i] = b[j], b[j] = temp;
      i++, j--;
    }
  }
  if (i < r) {
    sort(a, b, i, r);
  }
  if (j > l) {
    sort(a, b, l, j);
  }
}

void ins(int q[][2], int u, int v, int &h, int &t) {
  for (; h<=t && q[t][1]<u; t--);
  q[++t][1]=u;
  q[t][0] = v;
}

void del(int q[][2], int x, int &h, int &t) {
  for (; h<=t && q[h][0]<x; h++);
}

int main() {
#ifdef DEBUG
  freopen("3233.in", "r", stdin);
  freopen("3233.out", "w", stdout);
#endif

  static int l[maxm+1], r[maxm+1], f[maxn+1];
  int n, m;
  scanf("%d %d", &n, &m);
  for (int i=1; i<=n; i++) {
    scanf("%d %d", l+i, r+i);
  }

  static int que[maxn+1][2];
  for (int i=1; i<l[1]; i++) {
    f[i]=i;
  }
  for (int i=1, p=0, x=0, h=1, t=1; i<=n; i++) {
    for (; p<=n && r[p]<i; p++);
    if (l[p]<=i) {
      del(que, l[p-1], h, t);
      for (; x<l[p]; x++) {
	ins(que, f[x], x, h, t);
      }
      f[i] = max(que[h][1]+1, f[i-1]);
    } else {
      f[i] = f[i-1]+1;
    }
  }

  printf("%d", f[n]>0 ? f[n] : -1);

  fclose(stdin);
  fclose(stdout);
  return 0;
}
